
 /**  
 * Project Name:zhonghecrm  
 * File Name:LoginController.java  
 * Package Name:com.crm.controller  
 * Date:2016年10月13日上午10:19:34   
 *  
*/  
  
package com.crm.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.crm.model.SysMenu;
import com.crm.model.SysUser;
import com.crm.service.SysMenuService;
import com.crm.service.SysUserService;
import com.github.pagehelper.Page;

/**  
 * ClassName:LoginController <br/>  
 * Function: 登录控制器 <br/>  
 * Reason:   TODO ADD REASON. <br/>  
 * Date:     2016年10月13日 上午10:19:34 <br/>  
 * @author   hanlinxiu  
 * @version    
 * @since    JDK 1.8  
 * @see        
 */
@Controller
@RequestMapping("/login")
@SessionAttributes("currentUser")
public class LoginController {
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysMenuService sysMenuService;
	
	@RequestMapping("/index") 
	public String index(HttpServletRequest request){
		
		Session session = SecurityUtils.getSubject().getSession();
		
		SysUser currentUser = (SysUser)session.getAttribute("currentUser");
		
		System.out.println(currentUser.getRealName()); 
		System.out.println(session.getId());
		
		if(SecurityUtils.getSubject().isAuthenticated())
			return "forward:/login/successLogin";
		
		return "login";
	}
	
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public String login(HttpServletRequest request, ModelMap map){
		
		if(SecurityUtils.getSubject().isAuthenticated())
			return "forward:/login/successLogin";
		
		Cookie[] cookies = request.getCookies();
		if(null != cookies){
			for(int i=0; i<cookies.length; ++i){
				if(cookies[i].getName().equals("isRemember") && cookies[i].getValue().equals("y")){
					map.put("isChecked", "checked");
				}else if(cookies[i].getName().equals("username") && null != cookies[i].getValue()){
					map.put("userName", cookies[i].getValue());
				}else if(cookies[i].getName().equals("password") && null != cookies[i].getValue()){
					map.put("password", cookies[i].getValue());
				}
			}
		}
		
		return "login";
	}
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public String login(SysUser user, ModelMap map, HttpServletRequest request, HttpServletResponse response){
		
		UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPassword());
		//token.setRememberMe(true);
		
		Subject subject = SecurityUtils.getSubject();
		
		map.put("userName", user.getAccount());
		try{
			subject.login(token);
		}catch(UnknownAccountException  uae){
			map.put("msg", "账户未注册！");
		}catch(IncorrectCredentialsException ice){
			map.put("msg", "密码不正确！");
		}catch(LockedAccountException lae){
			map.put("msg", "账户不可用！");
		}catch(ExcessiveAttemptsException eae){
			map.put("msg", "错误次数过多！");
		}catch(AuthenticationException ae){
			ae.printStackTrace();
			map.put("msg", "用户名或密码错误！");
		}		
		
		if(subject.isAuthenticated()){
			
			//String smac = "";
			String sip = request.getHeader("X-Forwarded-For");   
			if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
				sip = request.getHeader("X-Real-IP");
			}   
			if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {
				sip = request.getHeader("Proxy-Client-IP");   
			}
			if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
			    sip = request.getHeader("WL-Proxy-Client-IP");   
			}   
			if(sip == null || sip.length() == 0 || "unknown".equalsIgnoreCase(sip)) {   
			    sip = request.getRemoteAddr();   
			}   
			
			/*UdpGetClientMacAddr umac;
			
			try {
				umac = new UdpGetClientMacAddr(sip);
				smac = umac.GetRemoteMacAddr();
			} catch (Exception e) {
				throw new RuntimeException("获取mac地址出错", e);
			}*/
			
			/*UdpGetClientMacAddr umac = new UdpGetClientMacAddr();
			smac = umac.getMACAddress(sip);*/
			
			SysUser currentUser = (SysUser)request.getSession().getAttribute("currentUser");
			
			currentUser.setIpAddress(sip);//更新ip地址
			//currentUser.setMacAddress(smac);//更新mac地址
			
			currentUser.setPreviousVisit(currentUser.getLastVisit());//更新上次访问时间
			currentUser.setLastVisit(new Date());//更新最后访问时间
			
			currentUser.setIsOnline("1");
			
			sysUserService.updateByPrimaryKey(currentUser);
			
			//cookie 是否记住账号密码
			String isRemember = request.getParameter("isRemember");	
			if(null != isRemember && isRemember.equals("y")){
				Cookie nameCookie = new Cookie("username", user.getAccount());
				nameCookie.setMaxAge(60 * 60 * 24 * 3);
				Cookie pwdCookie = new Cookie("password", user.getPassword());
				pwdCookie.setMaxAge(60 * 60 * 24 * 3);
				Cookie isRememberCookie = new Cookie("isRemember", isRemember);
				pwdCookie.setMaxAge(60 * 60 * 24 * 3);
				response.addCookie(nameCookie);
				response.addCookie(pwdCookie);
				response.addCookie(isRememberCookie);
			}else{
				Cookie[] cookies = request.getCookies();
				for(int i=0; i<cookies.length; ++i){
					if(cookies[i].getName().equals("username")){
						Cookie nameCookie = new Cookie("username", null);
						nameCookie.setMaxAge(0);
						response.addCookie(nameCookie);
					}else if(cookies[i].getName().equals("password")){
						Cookie pwdCookie = new Cookie("password", null);
						pwdCookie.setMaxAge(0);
						response.addCookie(pwdCookie);
					}else if(cookies[i].getName().equals("isRemember")){
						Cookie isRememberCookie = new Cookie("isRemember", null);
						isRememberCookie.setMaxAge(0);
						response.addCookie(isRememberCookie);
					}
				}
				
			}
			
			return "forward:/login/successLogin";
		}
			
		return "login";
	} 
	
	@RequestMapping("/logout") 
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		SysUser currentUser = (SysUser)request.getSession().getAttribute("currentUser");
		if(currentUser != null){
			sysUserService.updateIsOnline(currentUser.getUserId(), "0");
		}
		
		SecurityUtils.getSubject().logout();
		
		response.sendRedirect(request.getContextPath() + "/to_login.jsp");
	}
	
	/**
	 * 
	 * @Description : 验证不通过跳转
	 * @author zealot
	 * @param @return
	 * @return String
	 * @version 创建时间 : 2016年11月28日 下午4:40:14
	 * @thorws
	 */
	@RequestMapping("/tologin") 
	public String tologin(){
		
		SecurityUtils.getSubject().logout();
		
		return "tologin";
	}
	
	
	@RequestMapping("/successLogin")
	public String successLogin(Page<SysMenu> page, SysMenu t, ModelMap map){
		
		t.setEnable(null);
		List<SysMenu> list = (List<SysMenu>) sysMenuService.selectAll(page, t);
		
		map.put("list", list);
		
		return "main";
	}
	
}
  
